<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
use Hash;
class LoginController extends Controller
{
    //显示登录页面
   public function getIndex(){
        return view('admin/login/index');
   }
   //管理员登录操作
   public function postLogin(Request $request){
        //判断验证码是否正确
        if($request -> input('code') != session('code')){
            return back() -> withInput() -> with('error','验证码错误');
        }
        //通过管理员名称  获取数据
        $data = DB::table('admin_users') -> where('a_uname',$request->input('a_uname')) -> first();
        if(empty($data)){
            return back() -> withInput() -> with('error','管理员不存在');
        }
        //判断管理员密码是否正确
        if(!(Hash::check($request->input('a_upassword'),$data['a_upassword']))){
            return back() -> withInput() -> with('error','管理员密码不正确');
        }
        //将公理员信息存进session中
        session(['ad_user'=>$data]);
        //登录成功  页面跳转
        return redirect('/admin/user/index') -> with('success','登录成功');
   }
   //管理员修改面密码
   public function getAlter(){
      return view('admin/login/gaimi');
   }
   public function postPass(Request $request){
      $this->validate($request, [
          'password' => 'required',
          'a_upassword' => 'required',
          'repassword' => 'required|same:a_upassword'
       ],[
          'password.required' => '原密码必填',
          'a_upassword.required' => '新密码必填',
          'repassword.required' => '确认密码必填',
          'repassword.same' => '确认密码和新确认密码不一致'
       ]);
        if(!(Hash::check($request -> input('password'),session('ad_user')['a_upassword']))){
              return back() -> withInput() -> with('error','原密码不正确');
        }
        $arr['a_upassword'] = Hash::make($request->input('a_upassword'));
        $res = DB::table('admin_users') -> where('a_uid',session('ad_user')['a_uid']) -> update($arr);
        if($res){
            $request -> session() -> forget('ad_user');
            return redirect('/admin/login/index') -> with('error','原密码失效，重新登录');
        }else{
            return back() -> withInput() -> with('error','修改失败');
        }
   }
   public function getOut(Request $request){
       // dd($request -> session() -> has('ad_user'));
        $request -> session() -> forget('ad_user');
        // dd($request -> session() -> has('ad_user'));
        return redirect('/admin/login/index');
   }
}
